package com.zys.http.processor.jaxrs;

import cn.hutool.core.text.CharSequenceUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.PsiElement;
import com.intellij.psi.search.GlobalSearchScope;
import com.zys.http.constant.HttpEnum;
import com.zys.http.entity.param.ParamProperty;
import com.zys.http.entity.tree.MethodNodeData;
import com.zys.http.entity.velocity.MethodItem;
import com.zys.http.processor.AbstractKotlinApiProcessor;
import com.zys.http.tool.UrlTool;
import com.zys.http.tool.VelocityTool;
import com.zys.http.ui.tree.node.MethodNode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.idea.stubindex.KotlinAnnotationsIndex;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.psi.*;

import java.util.*;

/**
 * @author zhou ys
 * @since 2024-05-21
 */
public class JaxRsKotlinApiProcessor extends AbstractKotlinApiProcessor {
    private static final String CONSUMES = "Consumes";
    private static final String CONSUMES_1 = "javax.ws.rs.Consumes";
    private static final String CONSUMES_2 = "jakarta.ws.rs.Consumes";
    public static final JaxRsKotlinApiProcessor INSTANCE = new JaxRsKotlinApiProcessor();

    @Override
    @SuppressWarnings("deprecation")
    public List<? extends PsiElement> controllers(Project project, Module module) {
        Optional<GlobalSearchScope> scopeOp = Optional.of(module).map(Module::getModuleScope);
        Collection<KtAnnotationEntry> annotations = ApplicationManager.getApplication().runReadAction((Computable<Collection<KtAnnotationEntry>>) () -> {
            Collection<KtAnnotationEntry> all = new ArrayList<>();
            for (JaxRsEnums.Controller controller : JaxRsEnums.Controller.values()) {
                String shortClassName = controller.getShortClassName();
                all.addAll(scopeOp.map(ms -> KotlinAnnotationsIndex.getInstance().get(shortClassName, project, ms)).orElse(new ArrayList<>()));
            }
            return all;
        });

        return annotations.stream()
                .map(PsiElement::getParent)
                .map(KtDeclarationModifierList.class::cast)
                .map(KtDeclarationModifierList::getParent)
                .filter(KtClass.class::isInstance)
                .map(KtClass.class::cast)
                .toList();
    }

    @Override
    public String controllerPath(PsiElement psiElement) {
        if (!(psiElement instanceof KtClass ktClass)) {
            return "";
        }
        KtModifierList modifierList = ktClass.getModifierList();
        if (Objects.isNull(modifierList)) {
            return "";
        }
        List<KtAnnotationEntry> entries = modifierList.getAnnotationEntries();
        for (KtAnnotationEntry entry : entries) {
            Name shortName = entry.getShortName();
            if (Objects.isNull(shortName)) {
                continue;
            }
            String shorName = entry.getShortName().toString();
            if (JaxRsEnums.Controller.PATH_1.getClazz().endsWith(shorName)) {
                return annotationValue(entry, new String[]{VALUE_KEY});
            }
            if (JaxRsEnums.Controller.PATH_2.getClazz().endsWith(shorName)) {
                return annotationValue(entry, new String[]{VALUE_KEY});
            }
        }

        return "";
    }

    @Override
    public String methodPath(PsiElement element) {
        if (!(element instanceof KtNamedFunction function)) {
            return null;
        }
        List<KtAnnotationEntry> entries = function.getAnnotationEntries();
        for (KtAnnotationEntry o : entries) {
            Name shortName = o.getShortName();
            if (Objects.isNull(shortName)) {
                continue;
            }
            if (JaxRsEnums.Controller.PATH_1.getClazz().endsWith(shortName.asString())) {
                return annotationValue(o, new String[]{VALUE_KEY});
            }
            if (JaxRsEnums.Controller.PATH_2.getClazz().endsWith(shortName.asString())) {
                return annotationValue(o, new String[]{VALUE_KEY});
            }
        }
        return null;
    }

    @Override
    protected MethodNode createMethodNode(KtNamedFunction function, String controllerPath, String contextPath) {
        // 过滤某个符合的要求的注解
        KtModifierList modifierList = function.getModifierList();
        if (Objects.isNull(modifierList)) {
            return null;
        }
        KtAnnotationEntry pathAnno = null;
        String methodAnnoName = null;

        List<KtAnnotationEntry> entries = function.getAnnotationEntries();
        for (KtAnnotationEntry entry : entries) {
            Name shortName = entry.getShortName();
            if (Objects.isNull(shortName)) {
                continue;
            }
            String name = shortName.asString();
            if (JaxRsEnums.Controller.PATH_1.getClazz().endsWith(name)) {
                pathAnno = entry;
            }
            if (JaxRsEnums.Controller.PATH_2.getClazz().endsWith(name)) {
                pathAnno = entry;
            }

            if (JaxRsEnums.Method.contains(name)) {
                methodAnnoName = name;
            }
            if (JaxRsEnums.Method.contains("javax.ws.rs." + name)) {
                methodAnnoName = "javax.ws.rs." + name;
            }
            if (JaxRsEnums.Method.contains("jakarta.ws.rs." + name)) {
                methodAnnoName = "jakarta.ws.rs." + name;
            }
            if (Objects.nonNull(pathAnno) && Objects.nonNull(methodAnnoName)) {
                break;
            }
        }
        if (Objects.isNull(pathAnno) || Objects.isNull(methodAnnoName)) {
            return null;
        }
        String path = annotationValue(pathAnno, new String[]{VALUE_KEY});

        HttpEnum.HttpMethod httpMethod = JaxRsEnums.Method.get(methodAnnoName);
        MethodNodeData data = new MethodNodeData(httpMethod, path, controllerPath, contextPath);
        data.setPsiElement(function);
        data.setDescription(methodSwagger(function));
        return new MethodNode(data);
    }

    @Override
    protected void parameterParse(@NotNull KtParameter parameter, @NotNull Map<String, ParamProperty> map, boolean isJsonPretty) {
        String parameterName = parameter.getName();
        List<KtAnnotationEntry> entries = parameter.getAnnotationEntries().stream().filter(entry -> Objects.nonNull(entry.getShortName())).toList();

        // header
        KtAnnotationEntry headerAnno = entries.stream().filter(entry ->
                JaxRsEnums.Param.HEADER_PARAM_1.getClazz().equals(Objects.requireNonNull(entry.getShortName()).asString()) ||
                JaxRsEnums.Param.HEADER_PARAM_1.getShortName().equals(entry.getShortName().asString()) ||
                JaxRsEnums.Param.HEADER_PARAM_2.getClazz().equals(Objects.requireNonNull(entry.getShortName()).asString()) ||
                JaxRsEnums.Param.HEADER_PARAM_2.getShortName().equals(entry.getShortName().asString())
        ).findFirst().orElse(null);

        if (Objects.nonNull(headerAnno)) {
            ParamProperty property = map.getOrDefault(REQUEST_TYPE_KEY, null);
            if (property == null) {
                map.put(REQUEST_TYPE_KEY, new ParamProperty(HttpEnum.ContentType.APPLICATION_X_FORM_URLENCODED, HttpEnum.ParamUsage.HEADER));
            }
            map.put(parameterName, new ParamProperty("", HttpEnum.ParamUsage.HEADER));
            return;
        }

        // 2 如果有 @QueryParam 注解
        HttpEnum.ParamUsage paramUsage = HttpEnum.ParamUsage.URL;
        KtAnnotationEntry anno = entries.stream().filter(entry ->
                JaxRsEnums.Param.QUERY_PARAM_1.getClazz().equals(Objects.requireNonNull(entry.getShortName()).asString()) ||
                JaxRsEnums.Param.QUERY_PARAM_1.getShortName().equals(entry.getShortName().asString()) ||
                JaxRsEnums.Param.QUERY_PARAM_2.getClazz().equals(Objects.requireNonNull(entry.getShortName()).asString()) ||
                JaxRsEnums.Param.QUERY_PARAM_2.getShortName().equals(entry.getShortName().asString())
        ).findFirst().orElse(null);
        if (anno != null) {
            parameterName = annotationValue(anno, new String[]{VALUE_KEY});
        }

        // 3 如果有 @PathParam 注解
        anno = entries.stream().filter(entry ->
                JaxRsEnums.Param.PATH_PARAM_1.getClazz().equals(Objects.requireNonNull(entry.getShortName()).asString()) ||
                JaxRsEnums.Param.PATH_PARAM_1.getShortName().equals(entry.getShortName().asString()) ||
                JaxRsEnums.Param.PATH_PARAM_2.getClazz().equals(Objects.requireNonNull(entry.getShortName()).asString()) ||
                JaxRsEnums.Param.PATH_PARAM_2.getShortName().equals(entry.getShortName().asString())
        ).findFirst().orElse(null);
        if (anno != null) {
            parameterName = annotationValue(anno, new String[]{VALUE_KEY});
            paramUsage = HttpEnum.ParamUsage.PATH;
        }
        Object paramDefaultTypeValue = typeDefaultValue(parameter.getProject(), parameter);
        if (Objects.isNull(paramDefaultTypeValue)) {
            map.put(REQUEST_TYPE_KEY, new ParamProperty(HttpEnum.ContentType.APPLICATION_X_FORM_URLENCODED, HttpEnum.ParamUsage.HEADER));
            return;
        }

        KtNamedFunction parent = (KtNamedFunction) parameter.getParent().getParent();
        KtAnnotationEntry bodyAnno = parent.getAnnotationEntries().stream().filter(entry ->
                CONSUMES.equals(Objects.requireNonNull(entry.getShortName()).asString()) ||
                CONSUMES_1.equals(entry.getShortName().asString()) ||
                CONSUMES_2.equals(entry.getShortName().asString())
        ).findFirst().orElse(null);

        boolean isJson = false;
        if (Objects.nonNull(bodyAnno)) {
            String s = annotationValue(bodyAnno, new String[]{VALUE_KEY});
            isJson = s.contains(HttpEnum.ContentType.APPLICATION_JSON.getValue()) || "MediaType.APPLICATION_JSON".equals(s);
        }
        parameterParseResult(parameterName, paramDefaultTypeValue, isJson, isJsonPretty, map, paramUsage);
    }

    @Override
    protected MethodItem postmanMethodItem(KtNamedFunction function, String contextPath, String controllerPath) {
        KtModifierList modifierList = function.getModifierList();
        if (Objects.isNull(modifierList)) {
            return null;
        }
        MethodItem item = new MethodItem();
        List<KtAnnotationEntry> entries = function.getAnnotationEntries();
        // 方法名
        String methodSwagger = methodSwagger(function);
        methodSwagger = CharSequenceUtil.isEmpty(methodSwagger) ? function.getName() : methodSwagger;
        item.setName(methodSwagger);

        // 请求方式、请求uri、请求头类型
        String path = "";
        HttpEnum.HttpMethod httpMethod = null;
        for (KtAnnotationEntry entry : entries) {
            Name shortName = entry.getShortName();
            if (Objects.isNull(shortName)) {
                continue;
            }
            httpMethod = JaxRsEnums.Method.get(shortName.asString());
            if (Objects.isNull(httpMethod)) {
                httpMethod = JaxRsEnums.Method.get("javax.ws.rs." + shortName.asString());
            }
            if (Objects.isNull(httpMethod)) {
                httpMethod = JaxRsEnums.Method.get("jakarta.ws.rs." + shortName.asString());
            }
            if (JaxRsEnums.Controller.PATH_1.getClazz().endsWith(shortName.asString())) {
                path = annotationValue(entry, new String[]{VALUE_KEY});
            }
            if (JaxRsEnums.Controller.PATH_2.getClazz().endsWith(shortName.asString())) {
                path = annotationValue(entry, new String[]{VALUE_KEY});
            }
        }
        httpMethod = Objects.isNull(httpMethod) ? HttpEnum.HttpMethod.GET : httpMethod;
        item.setMethod(httpMethod.name());

        // 请求 uri
        item.setUri(UrlTool.buildMethodUri(contextPath, controllerPath, path));

        // 请求参数类型
        VelocityTool.buildParamProperty(function, item);
        return item;
    }
}
